package com.loper7.base.utils;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Pattern;

/**
 * 字符串操作工具包
 *
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class StringUtils {
    private final static Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };


    public static long getTime(String time) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            return format.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * @param time 2014/10/4 16:02:46
     * @return
     */
    public static long getTime2(String time) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        try {
            return format.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * @param time
     * @return yy-MM-dd HH:mm格式时间
     */
    public static String getTime(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date(time));
    }

    /**
     * @param time
     * @param type
     * @return
     */
    public static String getTime(long time, String type) {
        SimpleDateFormat format = new SimpleDateFormat(type);
        return format.format(new Date(time));
    }

    /**
     * 将字符串转为日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = null;
        if (TimeZoneUtil.isInEasternEightZones()) {
            time = toDate(sdate);
        } else {
            time = TimeZoneUtil.transformTime(toDate(sdate),
                    TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());
        }
        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前";
        } else if (days > 10) {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 返回long类型的今天的日期
     *
     * @return
     */
    public static long getToday() {
        Calendar cal = Calendar.getInstance();
        String curDate = dateFormater2.get().format(cal.getTime());
        curDate = curDate.replace("-", "");
        return Long.parseLong(curDate);
    }

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 将一个InputStream流转换成字符串
     *
     * @param is
     * @return
     */
    public static String toConvertString(InputStream is) {
        StringBuffer res = new StringBuffer();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader read = new BufferedReader(isr);
        try {
            String line;
            line = read.readLine();
            while (line != null) {
                res.append(line);
                line = read.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != isr) {
                    isr.close();
                    isr.close();
                }
                if (null != read) {
                    read.close();
                    read = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res.toString();
    }

    public static boolean isUrl(String path) {
        Pattern pattern = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
        return pattern.matcher(path).matches();
    }

    public static SpannableStringBuilder changeColor(String text, int begin, int end, int color) {
        if (begin > end) {
            Logger.e("SpannableStringBuilder error by:brgin > end *");
            return new SpannableStringBuilder("");
        }
        if (TextUtils.isEmpty(text)) {
            Logger.e("SpannableStringBuilder error by:text is empty *");
            return new SpannableStringBuilder("");
        }
        if (text.length() < end) {
            Logger.e("SpannableStringBuilder error by:text length < end *");
            return new SpannableStringBuilder("");
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
        ForegroundColorSpan span = new ForegroundColorSpan(color);
        builder.setSpan(span, begin, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }

    /**
     * textview 局部变大
     *
     * @param context 上下文
     * @param normal  普通文字
     * @param focus   变大文字
     * @param dp      变大dp
     * @return
     */
    public static Spannable setPortionBig(Context context, String normal, String focus, int dp) {
        Spannable span = new SpannableString(normal + focus);
        span.setSpan(new AbsoluteSizeSpan(DisplayUtil.dip2px(context, dp)), normal.length(), (normal + focus).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    }


    /**
     * double类型转两位小数字符
     *
     * @param d
     * @return
     */
    public static String float2String(float d, String pattern) {
        String defaultStr = "##0.0";
        if (!TextUtils.isEmpty(pattern)) {
            defaultStr = pattern;
        }
        return new DecimalFormat(defaultStr).format(d);
    }

    /**
     * 隐私显示身份证
     *
     * @param idcard
     * @return
     */
    public static String privateIdentificationCard(String idcard) {
        if (TextUtils.isEmpty(idcard) || idcard.length() < 15) {
            return idcard;
        }
        String start = idcard.substring(0, 2);
        String end = idcard.substring(idcard.length() - 3, idcard.length());
        idcard = start + "***********" + end;

        return idcard;
    }

    /**
     * 隐私显示真实姓名
     *
     * @param name
     * @return
     */
    public static String privateRealName(String name) {
        if (TextUtils.isEmpty(name)) {
            return name;
        }
        String showName = "";
        for (int i = 0; i < name.length(); i++) {
            if (i == name.length() - 1) {
                showName += name.substring(name.length() - 1, name.length());
            } else {
                showName += "*";
            }
        }
        return showName;
    }


    /**
     * 距离格式化
     *
     * @param distance 米
     * @return
     */
    public static String formatDistance(String distance) {
        double dis = 0;
        try {
            dis = Double.parseDouble(distance);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (dis >= 1000) {
            return double2String(dis / 1000) + "km";
        } else {
            return double2String(dis) + "m";
        }

    }

    /**
     * 格式化显示银行卡
     *
     * @param num
     * @param type 1银行卡 2支付宝
     * @return
     */
    public static String formatBankNumber(int type, String num) {
        String start, end;
        switch (type) {
            case 1:
                end = num.substring(num.length() - 4, num.length());
                num = "**** **** **** ****" + end;
                break;
            case 2:
                start = num.substring(0, 3);
                end = num.substring(num.length() - 3, num.length());
                num = start + "*****" + end;
                break;
        }
        return num;
    }

    /**
     * 格式化显示身份证
     *
     * @param num
     * @return
     */
    public static String formatIDCard(String num) {
        String start, end;
        start = num.substring(0, 1);
        end = num.substring(num.length() - 1, num.length());
        num = start + "****************" + end;

        return num;
    }

    /**
     * double类型转两位小数字符
     *
     * @param d
     * @return
     */
    public static String double2String(double d) {
        return new DecimalFormat("##0.00").format(d);
    }

    /**
     * double类型转两位小数字符
     *
     * @param d
     * @return
     */
    public static String double2String(String d) {
        if (TextUtils.isEmpty(d))
            return "--";
        return new DecimalFormat("##0.00").format(Double.parseDouble(d));
    }



}
